package com.yyfax.ph.personal.entrydetail;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.Loader;
import android.support.v7.widget.GridLayoutManager;
import android.view.View;
import android.widget.TextView;
import butterknife.BindView;
import com.aspsine.irecyclerview.IRecyclerView;
import com.aspsine.irecyclerview.OnLoadMoreListener;
import com.aspsine.irecyclerview.OnRefreshListener;
import com.yyfax.common.CLog;
import com.yyfax.common.recycler.StatesAdapter;
import com.yyfax.common.recyclerview.Divider;
import com.yyfax.common.recyclerview.FooterLoadMoreView;
import com.yyfax.common.tools.DensityUtil;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yyfax.infrastructure.mvp.PresenterLoader;
import com.yyfax.ph.R;
import com.yyfax.ph.base.adapter.BaseRetryRecyclerAdapter;
import com.yyfax.ph.base.YJPH;
import com.yyfax.ph.base.BaseYYFaxActivity;

import java.util.List;

/**
 * 子账号进件明细
 * Created by zhangxian on 2017/11/3.<br>
 * Copyright 2017 www.yylending.com. All Rights Reserved.<br><br>
 */
public class EntryDetailActivity extends BaseYYFaxActivity implements EntryDetailPresenter.View,
		OnRefreshListener, OnLoadMoreListener, BaseRetryRecyclerAdapter.RetryClickListener {
	private static final String TAG = EntryDetailActivity.class.getSimpleName();

	public final static String SUB_USER_ID = "sub_user_id";
	public final static String NAME = "name";
	public final static String BIND_DATE = "bind_date";
	public final static String APPLY_COUNT = "apply_count";
	public final static String LOAN_COUNT = "loan_count";
	private static final int LOADER_ID = 321;

	@BindView(R.id.name_tv)
	TextView mNameTv;
	@BindView(R.id.bind_date_tv)
	TextView mBindDateTv;
	@BindView(R.id.apply_count_tv)
	TextView mApplyCountTv;
	@BindView(R.id.loan_count_tv)
	TextView mLoanCountTv;

	@BindView(R.id.entry_detail_lv)
	IRecyclerView mListView;

	private EntryDetailAdapter mAdapter;

	private EntryDetailPresenter mPresenter;

	private String mSubUserId;
	private String mName;
	private String mBindDate;
	private int mApplyCount;
	private int mLoanCount;

	private BaseRetryRecyclerAdapter mViewStateAdapter;
	private FooterLoadMoreView mLoadMoreView;
	private int mPageNum = 1;
	private boolean mIsRefreshing = false;
	private int mPageSize = 20;


	public static void start(Activity aty, Intent intent) {
		aty.startActivity(intent);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getSupportLoaderManager().initLoader(LOADER_ID, null, this);
	}

	@Override
	public Loader<Presenter> onCreateLoader(int id, Bundle args) {
		return new PresenterLoader<>(this, new EntryDetailPresenter.Generator());
	}

	@Override
	public void onLoadFinished(Loader<Presenter> loader, Presenter data, int placeholder) {
		mPresenter = (EntryDetailPresenter) data;
		mPresenter.attach(this);
	}

	@Override
	public void pretreatmentAfterSetBaseView() {
		super.pretreatmentAfterSetBaseView();
		Intent i = getIntent();
		if (i != null) {
			if (i.hasExtra(EntryDetailActivity.SUB_USER_ID)) {
				mSubUserId = i.getStringExtra(EntryDetailActivity.SUB_USER_ID);
			}
			if (i.hasExtra(EntryDetailActivity.NAME)) {
				mName = i.getStringExtra(EntryDetailActivity.NAME);
			}
			if (i.hasExtra(EntryDetailActivity.BIND_DATE)) {
				mBindDate = i.getStringExtra(EntryDetailActivity.BIND_DATE);
			}
			if (i.hasExtra(EntryDetailActivity.APPLY_COUNT)) {
				mApplyCount = i.getIntExtra(EntryDetailActivity.APPLY_COUNT, 0);
			}
			if (i.hasExtra(EntryDetailActivity.LOAN_COUNT)) {
				mLoanCount = i.getIntExtra(EntryDetailActivity.LOAN_COUNT, 0);
			}
		}
	}

	@Override
	public int getContentViewRes() {
		return R.layout.entry_detail_activity;
	}

	@Override
	public void initContentView() {
		super.initContentView();
		setBtnRightVisible(false);
		setTitle(R.string.entry_detail);

		mNameTv.setText(mName);
		mBindDateTv.setText(getString(R.string.bind_time, mBindDate));
		mApplyCountTv.setText(String.valueOf(mApplyCount));
		mLoanCountTv.setText(String.valueOf(mLoanCount));

		mLoadMoreView = (FooterLoadMoreView) mListView.getLoadMoreFooterView();
		mListView.setLayoutManager(new GridLayoutManager(this, 1));
		mListView.addItemDecoration(new Divider(DensityUtil.dip2px(this, 0.5f), YJPH.getInstance().color(R.color.color_e6e6e6), false, 0, 0, 0, 0, 0));

		mAdapter = new EntryDetailAdapter();
		View noNetworkLayout = getLayoutInflater().inflate(R.layout.state_view_no_network, mListView, false);
		View emptyLayout = getLayoutInflater().inflate(R.layout.state_view_no_data, mListView, false);
		mViewStateAdapter = new BaseRetryRecyclerAdapter(mAdapter, null, emptyLayout, noNetworkLayout);
		mViewStateAdapter.setRetryClickListener(this);
		mListView.setIAdapter(mViewStateAdapter);

		mListView.setOnRefreshListener(this);
		mListView.setOnLoadMoreListener(this);
		mListView.setRefreshing(true);
	}


	@Override
	public void onBackBtnPressed() {
		super.onBackBtnPressed();
		finish();
	}

	@Override
	public void getEntryDetailSuccess(List<EntryDetailModel.EntryDetailBean> list) {
		//刷新
		if (mIsRefreshing) {
			refreshFinish();
			if (null != list && list.size() > 0) {
				mViewStateAdapter.setState(StatesAdapter.STATE_NORMAL);
				mAdapter.removeAll();
				mAdapter.addData(list);
				mAdapter.notifyDataSetChanged();
				mListView.scrollToPosition(0);
			} else {
				changeViewState(false);
			}
		}
		//上拉加载
		else {
			mLoadMoreView.setStatus(FooterLoadMoreView.Status.LOADING);
			if (null == list || list.size() == 0) {
				hadNoMore();
			} else {
				mViewStateAdapter.setState(StatesAdapter.STATE_NORMAL);
				mAdapter.addData(list);
				mAdapter.notifyDataSetChanged();
			}
		}
	}

	@Override
	public void getEntryDetailFailure(String tips) {
		mPageNum--;
		refreshFinish();
		mLoadMoreView.setStatus(FooterLoadMoreView.Status.GONE);
		if (mPageNum == 1) {
			changeViewState(true);
			showToast(R.string.load_failed);
		}
	}

	@Override
	public void onRefresh() {
		loadPage(true);
		mLoadMoreView.setStatus(FooterLoadMoreView.Status.GONE);
		mListView.setRefreshing(true);
		mIsRefreshing = true;
	}

	@Override
	public void onLoadMore() {
		if (FooterLoadMoreView.Status.THE_END != mLoadMoreView.getStatus()) {
			loadPage(false);
		} else {
			hadNoMore();
		}
		mIsRefreshing = false;
	}

	@Override
	public void onRetry() {
		onRefresh();
	}

	private void loadPage(boolean isRefresh) {
		mPageNum = isRefresh ? 1 : ++mPageNum;
		mPresenter.getEntryDetails(mSubUserId, mPageNum, mPageSize);
	}

	private void hadNoMore() {
		mLoadMoreView.setStatus(FooterLoadMoreView.Status.GONE);
		showToast(R.string.has_no_more);
	}

	private void refreshFinish() {
		mIsRefreshing = false;
		mListView.setRefreshing(false);
	}

	@Override
	public void onFunctionalError(Throwable e, boolean autoTips) {
		super.onFunctionalError(e, autoTips);
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				changeViewState(true);
			}
		});
	}

	private void changeViewState(boolean isLoadDataError) {
		if (mPageNum == 1) {
			refreshFinish();
			if (isLoadDataError) {
				mViewStateAdapter.setState(StatesAdapter.STATE_ERROR);
			} else {
				mViewStateAdapter.setState(StatesAdapter.STATE_EMPTY);
			}
		}
	}


	@Override
	protected void onDestroy() {
		super.onDestroy();
		getSupportLoaderManager().destroyLoader(LOADER_ID);
	}
}
